import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Select, Table, Switch, Avatar, Modal } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getStoreCatList, getStoreTypeList, getStoreList, handleSwitch, deteleStore, bindType } from '@/services/supplier/store/storeList'
import { router } from 'umi'
import { exportsExcel } from '@/utils/utils'

const { Option } = Select;

const StoreList = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [payWayList, setPayWayList] = useState([
    {
      id: 1,
      name: '机构结算'
    }, {
      id: 2,
      name: '平台结算'
    }
  ])
  const [catList, setCatList] = useState([])
  const [typeList, setTypeList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setpageSize] = useState(10)
  const [total, setTotal] = useState(1)
  const [record, setRecord] = useState([])
  const [visible, setVisible] = useState(false)

  // 表头
  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      align: 'center'
    },
    {
      title: 'LOGO',
      dataIndex: 'supplier_logo',
      key: 'supplier_logo',
      align: 'center',
      render: logo => <Avatar shape="square" size="large" src={logo} />
    },
    {
      title: '推广封面',
      dataIndex: 'showing_image',
      key: 'showing_image',
      align: 'center',
      render: logo => <Avatar shape="square" size="large" src={logo} />
    },
    {
      title: '门店名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '联系人',
      dataIndex: 'contact_person',
      key: 'contact_person',
      align: 'center'
    },
    {
      title: '商户名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      align: 'center'
    },
    {
      title: '所属分类',
      dataIndex: 'store_type',
      key: 'store_type',
      align: 'center'
    },
    {
      title: '是否推荐',
      dataIndex: 'isIndexRecommend',
      key: 'isIndexRecommend',
      align: 'center',
      render: (v) => {
        return (<Switch checked={v == 1 ? true : false} onChange={(v) => handleSwitchs(v, 'isIndexRecommend')} />)
      },
    },
    {
      title: '是否认证',
      dataIndex: 'isApprove',
      key: 'isApprove',
      align: 'center',
      render: (v) => {
        return (<Switch checked={v == 1 ? true : false} onChange={(v) => handleSwitchs(v, 'isApproveStore')} />)
      },
    },
    {
      title: '是否默认',
      dataIndex: 'is_default',
      key: 'is_default',
      align: 'center',
      render: (v) => {
        return (<Switch checked={v == 1 ? true : false} onChange={(v) => handleSwitchs(v, 'isDefault')} />)
      },
    },
    {
      title: '结算方式',
      dataIndex: 'payWay',
      key: 'payWay',
      align: 'center',
      render: () => <span>机构结算</span>
    },
    {
      title: '状态',
      dataIndex: 'store_status',
      key: 'store_status',
      align: 'center'
    }
  ]

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    await getStoreCatLists()
    await getStoreTypeLists()
    await getStoreLists()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      await getStoreLists(1, values.storeName, values.payWay, values.cat, values.type)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`门店`}>
          {getFieldDecorator(`storeName`, {})
            (<Input placeholder="请输入门店名称" />)}
        </Form.Item>
        <Form.Item label={`结算方式`}>
          {getFieldDecorator(`payWay`, {})
            (<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              placeholder="请选择"
            >
              {payWayList && payWayList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
        </Form.Item>
        <Form.Item label={`行业分类`}>
          {getFieldDecorator(`cat`, {})
            (<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              placeholder="请选择"
            >
              {catList && catList.map(r => <Option key={r.id} value={r.id}>{r.catName}</Option>)}
            </Select>)}
        </Form.Item>
        <Form.Item label={`分类`}>
          {getFieldDecorator(`type`, {})
            (<Select
              showSearch
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              placeholder="请选择"
            >
              {typeList && typeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
            </Select>)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    if (type !== 1 && record.length === 0) return
    switch (type) {
      // 新建门店
      case 1:
        router.push('/supplier/store/baseInfo')
        break
      // 编辑门店
      case 3:
        router.push({pathname: '/supplier/store/baseInfo', query: {id: record[0].id}})
        break
      // 删除门店
      case 4:
        await deteleStores(record[0].id)
        break
      // 绑定分类
      case 12:
        handleModal()
        break
      // 批量导出
      case 97:
        exportsExcel({
          columns,
          data: record,
          title: '门店列表'
        })
        break
    }
  }
  // 获取行业分类列表
  const getStoreCatLists = async () => {
    let res = await getStoreCatList()
    if (res.code === '0') {
      setCatList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取分类列表
  const getStoreTypeLists = async () => {
    let res = await getStoreTypeList()
    if (res.code === '0') {
      setTypeList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取门店列表
  const getStoreLists = async (pageNo = '1', storeName = '', parentCatId = '', storeType = '') => {
    let params = {
      pageNo,
      pageSize,
      storeName,
      parentCatId,
      storeType
    }
    let res = await getStoreList(params)
    if (res.code === '0') {
      await setStoreList(res.data)
      await setTotal(res.iTotalDisplayRecords)
    } else {
      alert(res.msg)
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      getStoreLists(page)
    }
  }
  // 操控开关
  const handleSwitchs = async (v, attr) => {
    if (record.length === 0) {
      alert('请选择一项再操作!')
      return
    }
    let params = {
      id: record[0].id
    }
    params[attr] = (v ? 1 : 0)
    let res = await handleSwitch(params)
    alert(res.msg)
    await getStoreLists()
  }
  // 删除门店
  const deteleStores = async (id) => {
    let params = {
      id
    }
    let res = await deteleStore(params)
    if (res.code === '0') {
      alert(res.msg)
      await getStoreLists()
    } else {
      alert(res.msg)
    }
  }
  // 操控弹出层
  const handleModal = () => {
    setVisible(!visible)
  }
  // 确认弹出层
  const handleOk = async () => {
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      if (!values.sort || !values.typeId) {
        alert('请填完整表单!')
        return
      }
      let params = {
        sort: values.sort,
        typeId: values.typeId,
        storeId: record[0].id
      }
      let res = await bindType(params)
      if (res.code === '0') {
        alert(res.msg)
        await getStoreLists()
      } else {
        alert(res.msg)
      }
    })
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={storeList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
      <Modal
        title="绑定分类"
        visible={visible}
        onOk={handleOk}
        onCancel={handleModal}
      >
        <Col span={24}>
          <Form.Item label="分类名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('typeId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
                onChange={getStoreLists}
              >
                { typeList && typeList.map(r => <Option key={r.id} value={r.id}>{r.typeName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="排序" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('sort', {})
              (<Input placeholder="请输入排序" />)}
          </Form.Item>
        </Col>
      </Modal>
    </PageHeaderWrapper>
  )
}

export default Form.create()(StoreList)
